package com.iweipan.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.v7.app.AlertDialog;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.iweipan.R;
import com.iweipan.fragment.PictureSelectFragment;
import com.iweipan.utils.snackbar.SnackbarUtil;
import com.iweipan.utils.sputils.SPUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.BitmapCallback;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;

import static com.iweipan.base.WPUrlBase.USER_ICON;
import static com.iweipan.base.WPUrlBase.USER_NAME_CHANGE;

/**
 * Created by xyb on 2016/12/27.
 */

public class WPUserInfoActivity extends PictureSelectFragment {

    @BindView(R.id.iv_section_title_back)
    ImageView ivSectionTitleBack;
    @BindView(R.id.ll_section_title_back)
    LinearLayout llSectionTitleBack;
    @BindView(R.id.tv_section_title_title)
    TextView tvSectionTitleTitle;
    @BindView(R.id.tv_section_title_right)
    TextView tvSectionTitleRight;
    @BindView(R.id.user_name)
    TextView userName;
    @BindView(R.id.ll_section_title_right)
    LinearLayout llSectionTitleRight;
    @BindView(R.id.rl_section_title)
    RelativeLayout rlSectionTitle;
    @BindView(R.id.user_icon)
    CircleImageView userIcon;
    @BindView(R.id.next_icon)
    ImageView nextIcon;
    @BindView(R.id.img_ray)
    RelativeLayout imgRay;
    @BindView(R.id.name_ray)
    RelativeLayout nameRay;

    private String user_icon;
    private String user_name;


    @OnClick({R.id.iv_section_title_back, R.id.tv_section_title_right, R.id.ll_section_title_right, R.id.name_ray, R.id.img_ray})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_section_title_right:
                break;
            case R.id.ll_section_title_right:
                break;
            case R.id.img_ray:
                selectPicture();
                break;
            case R.id.name_ray:

                initAlertDialog();

                break;
            case R.id.iv_section_title_back:
                if (WPUserInfoActivity.this != null) {
                    finish();
                }
                break;
        }
    }

    private void initAlertDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        //    通过LayoutInflater来加载一个xml的布局文件作为一个View对象
        View view = LayoutInflater.from(this).inflate(R.layout.userinfo_name_dialog, null);
        //    设置我们自己定义的布局文件作为弹出框的Content
        builder.setView(view);


        final AlertDialog alertDialog = builder.create();
        alertDialog.show();
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay();  //为获取屏幕宽、高
        android.view.WindowManager.LayoutParams p = alertDialog.getWindow().getAttributes();  //获取对话框当前的参数值
        p.width = (int) (d.getWidth() * 0.8);   //高度设置为屏幕的0.3

        alertDialog.getWindow().setAttributes(p);

        final EditText username = (EditText) view.findViewById(R.id.serach_et);
        ImageView finish = (ImageView) view.findViewById(R.id.finish_icon);
        Button rename = (Button) view.findViewById(R.id.rename_btn);
        finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (this != null) {
                    if (alertDialog.isShowing()) {
                        alertDialog.dismiss();
                    }
                }
            }
        });
        rename.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String name = username.getText().toString();
                if (name.length() < 3) {
                    SnackbarUtil.shortMake(username, "请输入标准昵称").show();
                    return;
                }
                String userId = (String) SPUtils.get(WPUserInfoActivity.this, "userId", "userId");

                OkHttpUtils.get()
                        .url(USER_NAME_CHANGE)
                        .addParams("userId", userId)
                        .addParams("userName", name)
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {

                            }

                            @Override
                            public void onResponse(String response, int id) {
//                                Log.e("WPUserInfoActivity", response);
                                alertDialog.dismiss();
                                userName.setText(name);
                                SPUtils.put(WPUserInfoActivity.this, "user_name", name);
                            }
                        });

            }
        });


    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_info;
    }

    @Override
    public void initViews() {
        user_icon = (String) SPUtils.get(this, "user_icon", "");
        Intent intent = getIntent();
        user_name = intent.getStringExtra("user_name");
        userName.setText(user_name);
        tvSectionTitleTitle.setText("个人信息");
    }

    @Override
    public void initEvents() {
        if (!user_icon.equals("")) {
            OkHttpUtils.get()
                    .url(user_icon)
                    .build()
                    .execute(new BitmapCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            e.printStackTrace();
                        }

                        @Override
                        public void onResponse(Bitmap response, int id) {
                            userIcon.setImageBitmap(response);
                        }
                    });
        }

        setOnPictureSelectedListener(new OnPictureSelectedListener() {
            @Override
            public void onPictureSelected(Uri fileUri, Bitmap bitmap) {
                userIcon.setImageBitmap(bitmap);

                try {
                    File file = new File(new URI(fileUri.toString()));
//                    Log.e(TAG, "file:" + file);
                    String userId = (String) SPUtils.get(WPUserInfoActivity.this, "userId", "userId");
                    if (!userId.equals("userId")) {
                        OkHttpUtils.post()
                                .url(USER_ICON)
                                .addFile("file", "cropImage.jpeg", file)
                                .addParams("userId", userId)
                                .build()
                                .execute(new StringCallback() {
                                    @Override
                                    public void onError(Call call, Exception e, int id) {
                                        e.printStackTrace();
                                    }

                                    @Override
                                    public void onResponse(String response, int id) {
//                                        Log.e(TAG, response);
                                        try {
                                            JSONObject jsonObject = new JSONObject(response);
                                            String path = jsonObject.getString("path");
                                            SPUtils.put(WPUserInfoActivity.this, "user_icon", path);
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });
                    }

                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }

                String encodedPath = fileUri.getEncodedPath();
                String decode = Uri.decode(encodedPath);
                Toast.makeText(mContext, decode, Toast.LENGTH_SHORT).show();
            }
        });
    }


}
